{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "da2b78b7",
   "metadata": {},
   "source": [
    "1. 匿名函数主要配合委托和事件使用,脱离这两部分不会使用匿名函数\n",
    "2. 匿名函数的缺点:匿名函数没有名字,使用委托接受后,没有办法移除这个匿名函数(匿名函数没有名字)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "80aec728",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello from anonymous function\n",
      "Hello from anonymous function with int: 5 and string: test\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "// 使用匿名函数,无返回值\n",
    "Action myAction = delegate(){\n",
    "    Console.WriteLine(\"Hello from anonymous function\");\n",
    "};\n",
    "myAction.Invoke();\n",
    "\n",
    "Action<int, string> myAction2 = delegate(int x, string y){\n",
    "    Console.WriteLine($\"Hello from anonymous function with int: {x} and string: {y}\");\n",
    "};\n",
    "myAction2.Invoke(5, \"test\");\n",
    "\n",
    "// 使用匿名函数,有返回值(最后一个参数是返回值)\n",
    "Func<int, string> myFunc = delegate(int x){\n",
    "    return (x * 2).ToString();\n",
    "};\n",
    "Console.WriteLine(myFunc.Invoke(5));"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "d92e990b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DoSomething with 5\n",
      "Hello from anonymous function\n",
      "Hello from getFunc\n"
     ]
    }
   ],
   "source": [
    "class Test{\n",
    "    public Action action = null;\n",
    "\n",
    "    public void DoSomething(int x,Action func){\n",
    "        Console.WriteLine($\"DoSomething with {x}\");\n",
    "        func();\n",
    "    }\n",
    "\n",
    "    public Action getFunc(){\n",
    "        return delegate(){\n",
    "            Console.WriteLine(\"Hello from getFunc\");\n",
    "        };\n",
    "    }\n",
    "}\n",
    " \n",
    "Test test = new Test();\n",
    "test.DoSomething(5, delegate(){\n",
    "    Console.WriteLine(\"Hello from anonymous function\");\n",
    "});\n",
    "\n",
    "test.getFunc().Invoke();"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".NET (C#)",
   "language": "C#",
   "name": ".net-csharp"
  },
  "language_info": {
   "name": "polyglot-notebook"
  },
  "polyglot_notebook": {
   "kernelInfo": {
    "defaultKernelName": "csharp",
    "items": [
     {
      "aliases": [],
      "name": "csharp"
     }
    ]
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
